package org.mms.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.mms.pojo.dto.UserDto;
import org.mms.pojo.entity.User;
import org.mms.pojo.request.UserLoginRequest;
import org.mms.pojo.request.UserRegisterRequest;
import org.mms.pojo.request.UserUpdateRequest;
import org.mms.pojo.util.ResponseMessage;
import org.mms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    @SentinelResource(value = "user:login", blockHandler = "handleUserLoginBlock")
    public ResponseMessage<UserDto> login(@RequestBody UserLoginRequest request) {
        return ResponseMessage.success(userService.login(request)
                .convert());
    }

    public ResponseMessage<UserDto> handleUserLoginBlock(UserLoginRequest request, BlockException ex) {
        return ResponseMessage.error(500, "请求太频繁，请稍后再试");
    }

    @PostMapping("/register")
    public ResponseMessage<UserDto> register(@RequestBody UserRegisterRequest request) {
        return ResponseMessage.success(userService.register(request)
                .convert());
    }

    @PutMapping("/password")
    public ResponseMessage<UserDto> updatePassword(@RequestBody UserUpdateRequest request) {
        return ResponseMessage.success(userService.updatePassword(request)
                .convert());
    }

    @GetMapping("/{id}")
    public ResponseMessage<UserDto> getById(@PathVariable("id") Long id) {
        return ResponseMessage.success(userService.getById(id)
                .convert());
    }

    @GetMapping
    public ResponseMessage<List<UserDto>> getAll() {
        return ResponseMessage.success(userService.getAll()
                .stream()
                .map(User::convert)
                .toList());
    }
}